Skip to main content

Full text of "Programming"

See other formats

Beginning Object-Oriented Programming: Make a Simple Game With Java 


Make Projects 

build, hack, tweak, share, discover. 

Beginning Object-Oriented 

Programming: Make a Simple 

Game With Java 

Written By: Chandler 


Any computer w/ internet (1) 


Object-oriented programming: a style of computer programming that uses different 
modules of code that build on each other or work together to create a program. OOP 

(for short) is commonly used today rather than line after line of code, to make programs 
more organized as collections of smaller units. This is an essential technique in 
programming today, and I will teach it to my best ability in this tutorial using the well-known 
programming language (and my favorite) Java. Note: this tutorial is currently a rough draft, 
but will be improved soon! Good luck! 

© Make Projects Page 1 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 1 — Beginning Object-Oriented Programming: Make a Simple Game 
With Java 

ORACLG' SUB Developer Network [SON) 

Sotant- Conwiun tJw - My SOU toxaM JoinaON 

SDNrk™ - EknmJrad CmWr 

Java SE Development Kit 5.0u22 

3ekel Platform ind Linguae* lw jr our download: 

PlnUnrm: Sal aOL- T | 

LjnouagH: MultulaiifpuiiQr 

I au'» id v, e JiivaOcifelgDni<nHKili..BuiZ Lirtwie Anrttmenl 



Getlkno Sl»rt«d? 
■ rii* ra j.iv.iCpi'Ii-i 

DmnkHd Re ion c* x 

* Dftivnloaa FAQS 

RC 1*1*0 HII6Uf#*l 


■ Solaris Dfffllopflt Cbiiibi 

■ Jivanx 

" WeD &*VSIiJB*r ft«oiir« 

* CwvslPperSsrylcw 

* Jflvacne online 

■ Sun Sludc-nl Developer 

• Setup: 

• Before you begin coding, you need 
something called the JDK This 
stands for Java Development Kit, 
and is Java's free way of letting 
you program in their language. Just 
click this link, and you will be led to 
the JDK 5.0 download page. 

• After downloading the JDK 
package, follow the instructions to 
install it on your computer. Make 
sure to use the default options for 
where you install the JDK, because 
that will come in handy later. 

Step 2 

Supported technologist * 


NMMH1I IDE DoMMiMd Bundles 
bvi EE C/C* + ft* 


9 N«8*J!ivs Plstt-pim SO* 



■1-' IbvsSE 



■fr JaviEE 


• ja-.i '■* 

,-□'- 3 Connected 

A.' C/C+ + 


& Groovy 

.', PHP 

a • 

Bundled vnrn 

■ (3'assRf n Server Qpe-n Source 


• * 

.., •pftCheTomOWTMl 

* • 





free, IS* "B free,* 

t [s&Lkt laitf uf in^ tna ]DE's Plugln Manager (Toali I Plujiu?). 

JDK 6 is required ra» inyamng and running me Java SE, la 

RuihIIh- Wnu can ttonnlajd stance long J&K or ir 
MttBtan* tPE JBVJ 55 BuntlHI . 

I :■!!.■! I I 1 : '>i ■■ I ■ i 1 1 : 

MetBcans Communfty Distributions are owoilflble under 
a Dull License tonsistino ol Uw jftTITIw" Pm'QBmern 
and DfetriMrtim license fCDDL) wl.O and GHU General 
Public LI«n K IGPL1 v?. 5«t ttMJ third. pa rwr^rfrr.f for 

external components Included In MeiBeans and their 

hfeifieans. EDE for Jaira SE. Learn 

• Setup, part 2: 

• Next, to make programming in 
Java easier, download and install 
NetBeans. NetBeans is an 
Integrated Development 
Environment, or IDE for short, that 
was created just for Java. 
NetBeans can be downloaded here . 
I'd recommend that you install the 
Java SE package if you're new to 

© Make Projects 

Page 2 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 3 

► id GameTest! 

■ a Heitawoftdepp 

' B JS(Mkcnirts_vi 

■ a RPSWln_U3 

- a build 

' 3 rpsuAn w3 


!*! RPSWfn.<Us5 
!5| RPS'.'/n_^. class 
□ RP5Wffi_ya.« 

* S empty 

* D generated- souses 

ft i*imujj.'.ij.jia 

' O disc 
' O nbpra\tct 
1 vc 

' ft buW.«ml 
3 manifest, m 

Recent Projects 

ft Eq Solve 

My NetBeans 

Install Pi u gins 

Add support forot her languages*^ technologies 
byinstaLb'ng plugins from ChsMetB«wwUpdKe 

I Show Or> Startup 

• Setup, part 3: 

• Simply open the NetBeans installer 
and walk through the process. It 
will ask you where to install 
NetBeans and where the JDK was 
installed. If you used the default 
option for this in the JDK installer, 
you should be fine accepting the 
default option here. Check the 
checkbox that instructs the 
installer to open NetBeans when 
you're done and click "Finish." The 
installer will close, NetBeans will 
open and we can get started! 

Step 4 

© Q»© New Java Application 


1. Choose Project 

2. Name and Location 

Name and Location 

Project Name: OOPExamplel 

Project Location: /home/watsonc/NetBeansProjects 

Project FoLder: /home/watsonc/MetBeansProjects/OOPExarnplel 

D Use Dedicated FoLder For Storing Libraries 

Libraries FoLder: 

DiFFerent users and projects can share the same compiLation Libra 

B Create Main Class |oopexampLe1.00PExample1 

Set as Main Project 

• Beginning your first project in 

• To start, go to File -> New -> 
Project. A window will open. Click 
"Next", and give your project a 
name (I will use "OOPExamplel"). 
Once that's done, click "Finish." A 
file ("OOPExamplel .Java", if you 
used that name) will appear. 

© Make Projects 

Page 3 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 5 


Q SB % *> <J" kdefaultconf 
x Services Classes 

> 85- <3- 

: iles 
O CameTest! 
a HelloWorldCpp 
Q JBookmarksvl 
G OOPExamplel 
^ RP5W!n_v3 
• O build 
T 'S classes 
T ^ rp5win_v3 
H RPSWin. class 
B RPSMr_v3.da55 
* fl empty 
► 3 gerieracgd-sources 

va [$ RPSWin_v3.]ava x ©main.cpp x [^J TTTVJinvl.jaua x ^jJBookmar 

► Q dist 

* d nbprojact 

► 13 src 

► S bulldxml 

OOPExampleljava- Navigator 


■ i£) OOPExamplel 

4) main(5thngQarg5) 








10 L 



13 H 

15 L 

16 n 

17 T 

19 L 



* To change this template, choose Tools | Templates 

* and open the template in the editor. 

package oopexamplel ; 

* gajthor watsonc 
public class OOPExamplel { 


(dparam args the command line arguments 

public static void wain (St ring [] args} { 
// TODO code application logic here 

• Goal: 

• Now we decide what will happen in 
our program. For this project, I will 
teach you how to make the game 
RPS (rock, paper, scissors): a 
simplistic yet fun game, great to 
learn to program. I will try to keep 
this tutorial simple to follow, and 
will explain the code as best I can. 

Step 6 

ft © -£ % ^ C <drf«uteconf-. 3T ft t> l&- ($■ 

« gi OOPExamplel jaft, 

-jj Files * *| Services CUsses 
■g. « □ GamtTtsM 
a * S HeUoWorWCpp 

... ge jgj. RPSWin_v3 Java * ^rnalrvcpp * ^gjTTTWJn_vi.]aua * |e£ JBook m ark s_v1 Java 

Its' jJ ■ ■ -^ %■- -r ^ & 4, 4; £l £1 D ±i -1 

■■ O OOPExampLet 


outputiBovasf 'scissors", "Tie!"); 

• 3- RP5VJTn ^3 


' 3 build 

w fli classes 


L } 

* ^ rpswin v3 

63:F) public void outputnovest String ■cpuout , String status) { 

fe RPSCPU.class 

64 String output = "I played ".concaTtcpuout) .corrcatj ' , 

} .concattstatus] ; 

@ RPSWSn.dass 

65 System. out'.printlnCout put) ; 

IS RPSVjin u3.tilass 

* O empty 

67 T. public Strina getCPUH»ve{ ) { 


imt choice = (intj Math.f!acr(Math.ra,Tdarnn*3] ; 
String rpsmove - "*; 





case Q: rpsmove = "rode"; croak; 

* □ dis.t 


case 1; rpsmov* - "psoei" ; break; 

* a nbprcj'4« 


default: r"pSfr.0v% = scissors ; break; 

► C3 r: 



► :._: txjILd.xml 



return rpsmove; 
1 } 


Navfgstor * * 

[•ic'f.bersvicw » 

» A CPU 

O compareinov-e5(5tringCPUMcive,5tn 

Q getCPUMoveO : String 

outpucmovesCStringcpuout, Strings 

■ Ci. OOPExamplel 

* main^CfingD args) 


put - OOPExamplel (run) * «| Tasks 




rsput your move (rock* paper or scissors!: 

J aper 


I played scissors. I win! 

3UILD SUCCESSFUL (total time: 5 seconds) 


• Code: 

• The following code may not make 
much sense if you are new to Java, 
but it will after I explain. The code 
has been attached to this project 
and can be accessed as 
RPSCode.pdf in the "Files" section. 
Open it, delete everything in your 
"OOPExamplel Java" file, and 
paste this code inside. Now, hit the 
"Run" button (it looks like a "Play" 
button on a DVD player, green), 
and some text will appear. You can 
now play Rock, Paper, Scissors 
with your computer! To play again, 
hit the "Run" button again. 

© Make Projects 

Page 4 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 7 

© Make Projects Page 5 of 1 3 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

package oopexamplel; 

import Java .util .Scanners- 
public class OOP Ex amp lei ( 

public static void main (Stringl ] args ) [ 
CPU cpul = new CPU [ ) ; 

Scanner scl = new Scanner (System. in) ; 
boolean validmove = falser- 
String userMove = "",- 
while (! validmove) ( 

System. out .printing" Input your move (rock, paper or 
scissors) : " t ; 

userMove = scl. nextLine O ; 
userMove = userMove . toLowerCase O ; 

if (userMove . equals ("rock" ) | | userMove .equals ( "paper" ) 
I I userMove, equals ("scissors")) { 

validmove ■ true; 

String CPUMove = cpul .get CPUMove () ; 
cpul . compa removes (CPUMove, userMove) ; 

© Make Projects 

• Explanation of the Code: 

• We made it through the 
programming! Next is to 
understand it. Look back at your 

• The first line just tells what 
"package" this piece of code is in. 
This simply tells where your code 
is stored. The next line is an 
import statement: it lets you use 
extra commands so that you can 
do more stuff with your program. 
Scanner (what it imports) is a 
module that reads what you type in 
when the program asks for your 

• public class OOPExamplel 

just starts a new class (a collection 
of functions and variables). Inside 
there is a method (function): 

public static void 

main ( String [ ] args ) . This is 

the main method, which runs when 
the program runs. 

• Inside is a bunch of code, the first 
of which is the line cpu cpul = 
new cpu( ) ;. This may look 
confusing, but all it does is create 
an instance (kind of like a personal 
copy) of the CPU class, which 
comes later. It also makes an 
instance of a Scanner: all that does 
is read what you type. These 
instances can be called by their 
names (cpul and scl, 

Page 6 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 


• Next, we define (make) two 
variables: vaiidmove (type 
boolean, either true or false) and 

userMove (a String (bunch Of 

text) that stores what the user's 
move is). 

• The code inside the loop prints the 
message instructing you to type 
your move, (the 

System. out .print In 

command), reads what you type 
(the nextLine command), 
converts it to lowercase (the 
toLowerCase) command, and 
tests it to see if the input is either 
"rock", "paper", or "scissors" (the 
if command; | | means "or"). If 
one of those is true, vaiidmove is 
set to true, and the loop ends. 
Phew! Now we have the user's 

• After the while loop, there is a 
command that defines another 
string: cPUMove. It's kind of self- 
explanatory what this string does: it 
stores the CPU's move. This line 
uses a method (function) called 
getcPUMove in the CPU Class 
(once again, a collection of 
variables and methods) to decide 
(randomly) what the computer's 
move should be. Finally, CPU's 

comparemoves method is Called 

and it is given the strings CPUMove 

© Make Projects Page 7 of 1 3 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

and userMove to let it know what 
moves have been made by the 

© Make Projects Page 8 of 1 3 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 8 

© Make Projects Page 9 of 1 3 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

class CPU( 

public void, comparemoves (String CPUMove, String userMove) 
if (userMove . equals {" rock" ) ) { 

if (CPUMove. equals ("rock") ) { 

outputmoves ( "rock" , "Tie ! ") ; 
if (CPUMove, equals ("paper") } { 

outputmoves ( "paper", "I win!"); 
if (CPUMove . equals ( "scissors" ) i { 

outputmoves ( "scissors", "You win!"); 
if (userMove. equals ("paper") } ( 

if (CPUMove. equals ("rock") ) { 

outputmoves ( "rock" , "You win!"); 

© Make Projects 

• Explanation of the Code, part 2: 

• (Note: don't rely on this image for 
the code, because I could not fit it 
all into one image). Now I will 
explain the CPU class! By the way, 
if you have any questions about 
what any of this terminology is, 
there is a great tutorial here about 
understanding OOP, created by the 
makers of Java. 

• The first method is called 

comparemoves. GueSS what it 

does? (Compares moves!). Inside 
are a bunch of if statements. 
Some of these are inside of each 
other, which might seem a little 
weird. Basically, all it does is see if 
the user played rock, paper, or 
scissors. Once it finds out which 
one he/she played, a bunch of if 
statements inside that find out what 
the CPU played and tell a different 
method, outputmoves, what to 
print on the screen. 

• Note that this method is called 

public void comparemoves. 
Void means that when it's called, it 
doesn't return anything. Returning a 
value means that the function 
passes back a value to the 
instruction that called it. The line 

String CPUMove = 

cpul . getCPUMove ( ) ; takes what 

was returned from the method 
getCPUMove in cpul and puts it in 

Page 10 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

the string cPUMove. Make sense? 

• Now let's talk about the 
outputmoves method, which the 

comparemoves method Calls. All it 

does is put together a string, 
output, and print it to the console, 
where you typed your moves 
earlier. The 

System, out. print In Statement 

is pretty simple, as all it does is 
print the string output. The 

String output = ... 

statement might be a bit confusing, 
however. It seems pretty normal, 
but what's this concat ( ) thing? 
It's a method that concatentates 
(fancy word for "pins onto the end") 
the thing in parentheses to the 
string before it. 

• This helps us put together the 
sentence "I played <move that the 
computer played>. <sentence that 
says who won>!" using the 
parameters that were passed to it 
(things that were given to it to work 

• Finally, we reach the getcPUMove 
method. This method randomly 
chooses what move the computer 
plays. The first line chooses a 
random number from just above 
to just below 3. Then, the number 
is floored, or the decimal part is 
removed, making it a random 
integer from to 2. Finally, it is 

© Make Projects Page 11 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

cast (changed) to an integer type 
(it wasn't completely an integer 
before because of the fractional 
part), and is stored into choice. 
Next, a string rpsmove is created 
and set to nothing (""). Finally, 
there is a switch statement, 
which is a variant of the if 
• All that it says is if choice equals 

0, then rpsmove = "rock". If it 

equals 1 , it is set to "paper", and if 
it is none of those (it must be 2), it 
is set to "scissors". Then it returns 
the move in the string rpsmove. 
Voila! We've returned a random 
move from the computer! But 
before I finish, I'd like to point out 
some things about the switch 
statement. Notice that the variable 
being tested is inside the 
parentheses next to the word 
switch, and that there are break 
statements after each case. All 
these do is clear the path for the 
next case. OK! We're done! 

© Make Projects Page 12 of 13 

Beginning Object-Oriented Programming: Make a Simple Game With Java 

Step 9 


Input your move (rock, paper or scissors): 


I played rock. Tie! 

BUILD SUCCESSFUL [total time: 3 seconds) 

• Wrap-up: 

• Thank you for reading this! It must 
have taken a great effort to read. It 
took me a great one to write. I hope 
that this project got you interested 
in Java programming (if it didn't 
bore you to death with all of the 
explanation), and that you will 
continue to explore this beautiful 
language. For a link to the 
beginning of a complete tutorial on 
Java, click here . 

• Good luck! 

This document was last generated on 2012-11-03 04:26:49 AM. 

© Make Projects 

Page 13 of 13